package zb.order.web;

import com.fasterxml.jackson.databind.ObjectMapper;


import com.zb.client.UserClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import zb.order.pojo.Order;
import zb.user.pojo.User;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private UserClient userClient;

    @Autowired
    private RestTemplate restTemplate;

    //    @HystrixCommand(fallbackMethod = "fallbackMethod")
    @GetMapping("{orderId}")
    public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
        // 根据id查询订单并返回
        Order order = new Order();
        order.setId(orderId);
        order.setName("XiaoMI");
        order.setPrice((long) 1999);
        order.setNum(3);
        order.setUserId((long) 1);
        User user = userClient.findById(order.getUserId());
        order.setUser(user);
        return order;
    }

//    public Order fallbackMethod(Long orderId){
//        Order order = new Order();
//        order.setName("熔断方法激活");
//        order.setId((long)orderId);
//        return order;
//    }

    @GetMapping("/k/{orderId}")
    public Order queryOrderByUserId2(@PathVariable("orderId") Long orderId) throws Exception{
        // 根据id查询订单并返回
        Order order = new Order();


        order.setId(orderId);
        order.setName("RedMI");
        order.setPrice((long) 999);
        order.setNum(1);
        order.setUserId((long) 5);
        String url = "http://duser:8081/user/" + order.getUserId();
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {
            String responseBody = EntityUtils.toString(response.getEntity());
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(responseBody, User.class);
            order.setUser(user);

        }

        return order;

    }
}